package cn.pugle.oj.leetcode;


import cn.pugle.oj.catalog.StackProblem;
import cn.pugle.oj.catalog.TreeProblem;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * 这个奇怪的栈
 *
 * @author tzp
 * @since 2020/10/12
 */
public class LC145 implements TreeProblem, StackProblem {
    public static class Pair<A, B> {
        public A a;
        public B b;

        public Pair(A a, B b) {
            this.a = a;
            this.b = b;
        }
    }

    public List<Integer> postorderTraversal(TreeNode root) {
        if (root == null) return Collections.emptyList();
        List<Integer> result = new ArrayList<>();
        LinkedList<Pair<TreeNode, Integer>> linkedList = new LinkedList<>();
        linkedList.addLast(new Pair<>(root, 0));

        Pair<TreeNode, Integer> cur;
        while (linkedList.size() != 0) {
            cur = linkedList.getLast();
            switch (cur.b) {
                case 0: {
                    if (cur.a.left != null) {
                        cur.b = 1;
                        linkedList.addLast(new Pair<>(cur.a.left, 0));
                        break;
                    }
                }
                case 1: {
                    if (cur.a.right != null) {
                        cur.b = 2;
                        linkedList.addLast(new Pair<>(cur.a.right, 0));
                        break;
                    }
                }
                case 2: {
                    linkedList.removeLast();
                    result.add(cur.a.val);
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
        Integer[] a = {1, 2, 4, 3, 5, 7, 10, 6, null, 8, null, 11, 9, 15, null, null, null, 12, null, null, null, 13, null, null, null, null, 14};
        TreeNode treeNode = TreeNode.arrayToTreeNode(a);
        System.out.println(new LC145().postorderTraversal(treeNode));
    }
}
